<template>
  <d2-container>
    <div class="order">
      <div class="free">
        <ul>
          <li class="first">
            <span>电商平台:</span>
            <el-radio @change="typelist(1)" v-model="radio1" label="1" border>淘宝/天猫</el-radio>
            <el-radio @change="typelist(2)" v-model="radio1" label="2" border>拼多多</el-radio>
            <el-radio @change="typelist(3)" v-model="radio1" label="3" border>阿里</el-radio>
            <el-radio @change="typelist(4)" v-model="radio1" label="4" border>京东</el-radio>
            <el-radio @change="typelist(5)" v-model="radio1" label="5" border>其他</el-radio>
          </li>
          <li class="first">
            <span>代发快递:</span>
            <el-select v-model="kuaidi_id" @change="empry_typecangks($event)" placeholder="请选择代发快递"
                       style="width:500px;">
              <el-option
                v-for="item in expressList"
                :label="item.name+''+item.text"
                :value="item.kdid"
                :key="item.kdid">
              </el-option>
            </el-select>
          </li>
          <li class="first" style="display:flex;align-items:center;justify-content: flex-start;">
            <span>快递说明:</span>
            <div class="tishi_content" style="width: 729px;" v-if="remarks != ''">{{remarks}}</div>
            <div class="tishi_content" style="width: 729px;" v-if="remarks == ''">暂无说明</div>
          </li>
          <li class="first">
            <span>发货地址:</span>
            <el-select size="small" v-model="fahuoDZ" clearable placeholder="请选择发货地址">
              <el-option v-for="item in fahuoDZList" :key="item.id"
                         :label="item.sender_prov+'-'+item.sender_city+'-'+item.sender_county+'-'+item.sender_address"
                         :value="item.id"></el-option>
            </el-select>
            <span>订单号：</span>
            <el-input type="text" v-model="goodsNum" placeholder="请输入订单号"></el-input>
          </li>
          <li class="first" style="width:100%;display:flex;align-items: center;">
            <span>代发地址:</span>
            <div class="tishi_content" style="width: 729px;" v-if="optiontion.length == 0 && kuaidi_id !=0">暂无代发地址</div>
            <div class="tishi_content" style="width: 729px;" v-if="optiontion.length == 0 && kuaidi_id ==0">请先选择代发快递
            </div>
            <el-select v-model="cang_id" @change="empry_typegoodss($event)" placeholder="请选择代发地址" v-if="optiontion.length > 0"
                       style="width:500px;">
              <el-option
                v-for="item in optiontion"
                :key="item.warehouse"
                :label="item.name+'　　'+item.province+item.city+item.district+item.address"
                :value="item.warehouse">
              </el-option>
            </el-select>
          </li>
          <li class="first" style="display:flex;align-items: center;">
            <span>实物礼品:</span>
            <div class="tishi_content" style="width: 729px;" v-if="optioning.length == 0 && cang_id==''">请先选择代发地址</div>
            <div class="tishi_content" style="width: 729px;" v-if="optioning.length == 0 && cang_id!=''">暂无礼品</div>
            <div style="width:100%;flex-wrap:wrap;display:flex;height:250px;overflow-y:scroll;"
                 v-if="optioning.length > 0">
              <div :class="{active:flag==index}" @click="clicks(index,i.gift)"
                   style="width:150px;display:flex;flex-direction: column;align-items:center;justify-content:flex-start;border:1px solid red;"
                   v-for="(i,index) in optioning">
                <img style="width:100%;height:150px;" :src="i.image" alt="">
                <p style="font-size:14px;">{{i.name}} {{i.price}}元/件</p>
              </div>
            </div>
          </li>
          <li class="first">
            <div style="display:flex;">
              <span>一键粘贴</span>
              <span style="color:red;display:inline-block;width:100%;text-align:left;">*格式：姓名 电话 地址（姓名电话地址之间以逗号隔开，开头不能添加空格）按照  千牛后台粘贴 列如：
              <span style="color:red;display:inline-block;width:100%;text-align:left;margin:10px;">
                刘某某，86-13313131313，山西省 长治市 屯留县 西贾乡 山西省西西市西留区西西乡东贾村100号 ，000000</span>
              </span>
            </div>
            <el-input size="small" v-model="ardess" type="textarea" placeholder="请输入地址"
                      @blur="addressanalysiss"></el-input>
          </li>
          <li class="second">
            <span>收件人</span>
            <el-input size="small" v-model="recipient" placeholder="请输入收件人姓名"></el-input>
            <span>手机号码</span>
            <el-input size="small" v-model="phoneNum" placeholder="请输入手机号码"></el-input>
          </li>
          <li class="second">
            <el-row>
              <span>省份</span>
              <el-select v-model="addressor_state" filterable placeholder="请选择" @change="selectProvimce">
                <el-option
                  v-for="(item,index) of provincearr"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <span>市</span>
              <el-select v-model="addressor_city" filterable placeholder="请选择" @change="selectcity">
                <el-option v-for="(item,index) of cityarr" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
              <span>区</span>
              <el-select placeholder="请选择" filterable v-model="addressor_district">
                <el-option
                  v-for="(item,index) of regionarr"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-row>
          </li>
          <li class="second">
            <span>详细地址</span>
            <el-input size="small" v-model="detailArdess" placeholder="请输入地址"></el-input>
          </li>
          <li style="text-align:center;list-style: none;">
            <el-button type="primary" @click="createds()" :loading="loading">创建订单</el-button>
          </li>
        </ul>
      </div>
      <el-dialog
        title="付款提示"
        width="20%"
        :visible.sync="dialogVisible">
        <div style="width:100%;margin:0 auto">
          <span>本次提交您需支付{{price}}元！</span>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onCreated" :loading="loading">确 定</el-button>
         </span>
      </el-dialog>
    </div>
  </d2-container>
</template>

<script>
  import {
    shoplist,
    dt_price,
    addresslist,
    empry_typegoods,
    empry_typecangk,
    waybill_list,
    kbcalculation,
    userinfo,
    empry_typelist,
    addressanalysis,
    order_create
  } from '@/api/api'
  import doConnect from "../../../router/printer/printer.js";
  import {province} from '@/api/map.js'

  export default {
    data() {
      return {
        flag: 0,
        cityarr: [],
        radio1: '1',
        regionarr: [],
        provinceValue: '',
        cityValue: '',
        cang_id: "",
        RegionValue: '',
        provincearr: [],
        ardess: '', // 全部地址
        price: "",
        dialogVisible: false,
        recipient: '', //收件人
        phoneNum: '', // 手机号码
        province: [],
        shi1: [],
        qu1: [],
        city: "",
        block: "",
        goods_id: "",
        fahuoDZ: "",
        detailArdess: '',//详细地址
        custom: '',// 自定义
        addressor_state: '',
        addressor_city: '',
        addressor_district: '',
        mainHeight: document.body.clientHeight - 520 + 'px',
        tableData: [],
        fahuoDZList: [],
        express: '',
        totalItem: 0,
        pageIndex: 1,
        pageSize: 100,
        expressList: [],
        goodsName: '',
        goodsNum: '',
        addrDetail: '',
        shopName: '',
        shopList: [],
        remarks: "请先选择代发快递",
        kuaidi_id: '',
        types:"",
        selectvalue: "",
        searchNum: '',
        optiontion: [],
        optioning: [],
        loading: false,
      }
    },
    created() {
      this.provincearr = province
      this.getShopNameData()
      this.typelist(1)
      this.fahuoDZLists()
      this.waybill_lists()
      this.getUser()
      this.dt_prices()
    },
    methods: {
      typelist(val){
        console.log(val);
        let params={
          platform:val.toString()
        }
        empry_typelist(params).then((res) => {
          console.log(Object.entries(res.Data));
          this.expressList = res.Data
        })
      },
      createds() {
        this.dialogVisible = true;
        this.kbcalculations()
      },
      selectval(val) {
        this.selectvalue = val
      },
      clicks(val, gift) {
        this.flag = val
        this.goods_id = gift
      },
      //计算价格
      kbcalculations() {
        let params = {
          ckid: Number(this.cang_id),
          kdid: Number(this.kuaidi_id),
          goodsid: Number(this.goods_id),
          type: Number(this.radio1),
        }
        kbcalculation(params).then(res => {
          if (res.Status == 200) {
              this.price = res.Data
          } else {
            this.$message.error(res.Message)
          }
        })
      },
      addressanalysiss() {
        console.log(this.ardess.split(/[\n]/));
        let params = {
          urls: this.ardess
        }
        addressanalysis(params).then((res) => {
          if(res.Status == 200){
            this.recipient = res.Data.receiver_name
            this.phoneNum = res.Data.receiver_phone
            this.addressor_state = res.Data.receiver_state
            this.addressor_city = res.Data.receiver_city
            this.addressor_district = res.Data.receiver_district
            this.detailArdess = res.Data.receiver_address
          }else{
             this.$message({
                type:'error',
                message:res.Message
             })
          }
        })
      },
      selectProvimce(id) {
        this.cityarr = [];
        this.regionarr = [];
        this.cityValue = '';
        this.RegionValue = '';
        for (let item of this.provincearr) {
          if (id == item.id) {
            this.cityarr = item.children
          }
        }
      },
      selectcity(id) {
        this.regionarr = [];
        this.RegionValue = '';
        for (let item of this.cityarr) {
          if (id == item.id) {
            this.regionarr = item.children
          }
        }
      },
      getUser() {
        userinfo().then(res => {
          if (res.Status == 200) {
            this.$store.commit('Money', JSON.stringify(res.Data.Money))
          } else {
            this.$message.error(res.Message)
          }
        })
      },
      //发货列表
      waybill_lists() {
        let params = {
          Page: 1,
          status: "",
          ordernum: "",
          waybillnum: "",
          times: []
        }
        waybill_list(params).then((res) => {
          this.tableData = res.Data
        })
      },
      //发货地址
      fahuoDZLists() {
        let params = {
          page: 1,
        }
        addresslist(params).then((res) => {
          this.fahuoDZList = res.Data
        })
      },
      // 获取店铺名称
      getShopNameData() {
        shoplist().then(res => {
          if (res.Status == 200) {
            this.shopList = res.Data
          }
        });
      },
      //时间戳转换
      time(time) {
        var timestamp4 = new Date(time * 1000);//直接用 new Date(时间戳) 格式转化获得当前时间
        return timestamp4.toLocaleDateString().replace(/\//g, "-") + " " + timestamp4.toTimeString().substr(0, 8)
      },
      find(str, cha, num) {
        var x = str.indexOf(cha);
        for (var i = 0; i < num; i++) {
          x = str.indexOf(cha, x + 1);
        }
        return x;
      },
      // 分页
      pageChange(pageIndex) {
        this.pageIndex = pageIndex
        this.waybill_lists()
      },
      pageSizeChange(pageSize) {
        this.pageIndex = 1
        this.pageSize = pageSize
        this.waybill_lists()
      },
      //价格列表
      dt_prices() {
        dt_price().then(res => {
          console.log(res);
        })
      },
      // 创建订单
      onCreated() {
        this.loading = true
        // doConnect.doConnect()
        if (this.goodsNum == '') {
          this.$message({
            type: "error",
            message: "订单号不能为空！"
          })
        } else if (this.kuaidi_id == '') {
          this.$message({
            type: "error",
            message: "快递不能为空！"
          })
        } else {
          let params
          if (this.ardess == '') {
            params = {
              form_type:Number(this.radio1),
              type: Number(this.types),
              kua_id: Number(this.kuaidi_id),//请选择快递
              cang_id: Number(this.cang_id),//请选择你想的快递仓库
              goods_id: Number(this.goods_id),//请选择商品
              address_id: this.fahuoDZ,
              goods_name: this.goodsNum,//内件详情，不可以为空
              goods_weight: '1',//商品重量，不可以为空
              goods_number: '1',//商品数量，不可以为空
              order_sn: this.goodsNum,//订单号，不可以为空
              rec_name: this.recipient,//收货人，不可以为空
              rec_mobile: this.phoneNum.replace(/\s/g, ""),//收货人手机，不可以为空
              rec_province: this.addressor_state,//收货人省份，不可以为空
              rec_city: this.addressor_city.replace(/\s/g, ""),//收货人城市，不可以为空
              rec_district: this.addressor_district,//收货人区/县/镇，不可以为空
              receive_address: this.detailArdess.replace(/\s/g, "")//收件人详细地址，不可以为空
            }
          } else {
            params = {
              form_type:Number(this.radio1),
              type: Number(this.types),
              kua_id: Number(this.kuaidi_id),//请选择快递
              cang_id: Number(this.cang_id),//请选择你想的快递仓库
              goods_id: Number(this.goods_id),//请选择商品
              address_id: this.fahuoDZ,//发货地址
              goods_name: this.goodsNum,//内件详情，不可以为空
              goods_weight: '1',//商品重量，不可以为空
              goods_number: '1',//商品数量，不可以为空
              order_sn: this.goodsNum,//订单号，不可以为空
              rec_name: this.recipient,//收货人，不可以为空
              rec_mobile: this.phoneNum.replace(/\s/g, ""),//收货人手机，不可以为空
              rec_province: this.addressor_state,//收货人省份，不可以为空
              rec_city: this.addressor_city.replace(/\s/g, ""),//收货人城市，不可以为空
              rec_district: this.addressor_district,//收货人区/县/镇，不可以为空
              receive_address: this.detailArdess.replace(/\s/g, "")//收件人详细地址，不可以为空
            }
          }
          order_create(params).then(data => {
            this.loading = false
            if (data.Status == 200) {
              this.$message({
                type: "success",
                offset: 200,
                duration: 1000,
                message: data.Message
              })
              this.dialogVisible = false
              this.waybill_lists()
              this.getUser()
            } else {
              this.$message({
                type: "error",
                offset: 300,
                duration: 2000,
                message: data.Message
              })
            }
          })
        }
      },
      //删除
      delClick(row) {
        let params = {
          id: row.id
        }
        this.$axios.post('api/kdn/DelectPrinter', params).then(res => {
          if (res.data.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功！"
            })
            this.getTableData()
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            })
          }
        })
      },
      //礼品
      empry_typegoodss(val) {
        let params = {
          ckid: this.cang_id,
          type: this.radio1
        }
        empry_typegoods(params).then(res => {
          this.optioning = res.Data
          console.log(res);
        })
      },
      //仓库
      empry_typecangks(e) {
        let obj = {};
        obj = this.expressList.find((item) => {
          return item.kdid === e;
        });
        this.remarks = obj.remarks
        this.types = obj.type
        let params = {
          kdid: e,
        }
        empry_typecangk(params).then(res => {
          this.optiontion = res.Data
        })
      },
      //搜索
      searchClick() {
        let params = {
          receiver_name: this.searchNum
        }
        this.getTableData(params)
      }
    }
  }
</script>
<style scoped lang="scss">
  .tishi_content {
    border-radius: 3px;
    padding: 8px 10px;
    font-size: 15px;
    line-height: 25px;
    background: #fbfbfb;
    color: #fb00ff;
    font-weight: bold;
    border: 1px solid #ececec;
    width: 669px;
  }

  .active {
    background: red;
    color: white;
  }

  .order {
    background-color: #fff;
    padding: 15px 40px;

    .el-pagination {
      margin-top: 15px;
      text-align: right;
    }

    .free {
      border: 1px solid #ccc;
      padding: 30px 10px 0;
      margin-bottom: 40px;

      li {
        margin-bottom: 20px;

        span {
          display: inline-block;
          width: 80px;
          text-align: right;
          margin-right: 10px;
        }
      }

      .first {
        list-style: none;

        .el-input {
          width: 60%;
        }
      }

      .second {
        .el-input {
          width: 20%;
        }
      }
    }
  }

  .search {
    margin-bottom: 10px;
  }
</style>
<style>
  .el-textarea__inner {
    min-height: 150px;
  }
</style>
